/**
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.manager;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.legendshop.oa.constants.AttachmentDefinition;
import com.legendshop.oa.constants.AttachmentDefinitionFactory;
import com.legendshop.oa.constants.AttachmentTypeEnum;
import com.legendshop.oa.constants.Constants;
import com.legendshop.oa.constants.ImageTypeEnum;
import com.legendshop.oa.handler.AttachmentManager;
import com.legendshop.oa.model.Attachment;
import com.legendshop.oa.security.UserManager;
import com.legendshop.oa.service.AttachmentService;
import com.legendshop.util.AppUtils;

/**
 * 公共文件管理 抽象类
 *
 */
public abstract class CommonAttachmentManagerImpl implements AttachmentManager {

	protected final Logger log = LoggerFactory.getLogger(CommonAttachmentManagerImpl.class);

	/**
	 * 附件服务.
	 */
	protected AttachmentService attachmentService;

	/**
	 * 图片比例列表.
	 */
	protected Map<String, List<Integer>> scaleList;

	/**
	 * 根据文件名删除附件表记录
	 */
	@Override
	public void delAttachmentByFilePath(String filePath) {
		attachmentService.deleteAttachment(filePath);
	}

	/**
	 * 保存到附件表
	 * 
	 * @param userName
	 *            用户名
	 * @param filePath
	 *            文件路径
	 * @param file
	 * @param type
	 *            附件类型
	 */
	@Override
	public Long saveAttachment(Long userId, String userName, String filePath, MultipartFile file, AttachmentTypeEnum type, ImageTypeEnum imgType) {
		return this.saveAttachment(userId, userName, filePath, file, type, 0, imgType);
	}

	/**
	 * 保存到附件表,默认是图片
	 * 
	 * @param userName
	 *            用户名
	 * @param filePath
	 *            文件路径
	 * @param file
	 * @param type
	 *            附件类型
	 */
	@Override
	public Long saveAttachment(Long userId, String userName, String filePath, MultipartFile file, AttachmentTypeEnum type) {
		return this.saveAttachment(userId, userName, filePath, file, type, 0, ImageTypeEnum.IMG);
	}

	/**
	 * 逻辑删除文件,修改附件表的状态
	 * 
	 * @param fileName
	 *            文件路径,包括文件名
	 */
	@Override
	public void deleteLogical(String fileName) {
		attachmentService.updateAttachmentStsByFilePath(fileName, 0);
	}

	/**
	 * 保存到附件表
	 * 
	 * @param userName
	 *            用户名
	 * @param filePath
	 *            文件路径
	 * @param file
	 * @param type
	 *            附件类型
	 * @param treeId
	 *            节点id
	 */
	@Override
	public Long saveAttachment(Long userId, String userName, String filePath, MultipartFile file, AttachmentTypeEnum type, long treeId, ImageTypeEnum imgType) {
		if (AppUtils.isBlank(filePath) || AppUtils.isBlank(file)) {
			log.warn("can not save attachment without file");
			return -1l;
		}
		if (Constants.PHOTO_FORMAT_ERR.equals(filePath)) {
			log.warn("can not save attachment");
			return -3l;
		}

		String fileName = file.getOriginalFilename();
		Attachment attachment = new Attachment();
		if (AppUtils.isBlank(userName)) {
			userName = UserManager.getUserName();
		}

		if (AppUtils.isBlank(userName)) {
			log.warn("can not save attachment without login");
			return -2l;
		}

		attachment.setUserName(userName);
		attachment.setUserId(userId);
		attachment.setRecDate(new Date());
		attachment.setExt(file.getOriginalFilename().substring(fileName.lastIndexOf(".") + 1).toLowerCase());
		attachment.setFilePath(filePath);
		attachment.setFileSize(file.getSize());
		attachment.setStatus(true);
		attachment.setFileName(file.getOriginalFilename());
		attachment.setTreeId(treeId);
		attachment.setFileType(type.value());
		attachment.setIsManaged(type.type());
		attachment.setImgType(imgType.value());
		try {
			BufferedImage image = ImageIO.read(file.getInputStream());
			attachment.setWidth(Long.valueOf(image.getWidth()));
			attachment.setHeight(Long.valueOf(image.getHeight()));
		} catch (IOException e) {
			log.error("get image width and height error {}", e.toString());
		} catch (Exception e) {
			log.error("attach is not image ", e.toString());
		}
		return attachmentService.saveAttachment(attachment);// 保存到附件表
	}

	/**
	 * 保存到附件表
	 * 
	 * @param userName
	 *            用户名
	 * @param filePath
	 *            文件路径
	 * @param is
	 *            文件流
	 * @param fileName
	 *            文件名
	 * @param fileSize
	 *            文件大小
	 * @param type
	 *            附件类型
	 */
	@Override
	public Long saveAttachment(Long userId,String userName, String filePath, InputStream is, String fileName, long fileSize, AttachmentTypeEnum type,
			ImageTypeEnum imgType) {

		if (AppUtils.isBlank(userName)) {
			userName = UserManager.getUserName();
		}
		if (AppUtils.isBlank(userName)) {
			log.warn("can not save attachment without login");
			return -2l;
		}
		if (AppUtils.isBlank(filePath) || AppUtils.isBlank(is)) {
			log.warn("can not save attachment without file");
			return -1l;
		}

		if (Constants.PHOTO_FORMAT_ERR.equals(filePath)) {
			log.warn("can not save attachment");
			return -3l;
		}

		Attachment attachment = new Attachment();
		attachment.setUserName(userName);
		attachment.setUserId(userId);
		attachment.setRecDate(new Date());
		attachment.setExt(fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase());
		attachment.setFileSize(fileSize);
		attachment.setStatus(true);
		attachment.setFileName(fileName);
		attachment.setTreeId(0l);
		attachment.setFileType(type.value());
		attachment.setIsManaged(type.type());
		attachment.setImgType(imgType.value());
		AttachmentDefinition attachmentDefinition = AttachmentDefinitionFactory.getInstance()
				.getAttachmentDefinitionByType(fileName.substring(fileName.lastIndexOf(".")));
		attachment.setImgType(attachmentDefinition.getType());
		if (ImageTypeEnum.VIDEO.value().equals(attachmentDefinition.getType())) {// 目前分为2种情况
			attachment.setFilePath(filePath.substring(0, filePath.lastIndexOf(".")) + ".png");// 视频首帧放在图片的位置
			attachment.setVideoPath(filePath);// 将视频的路径放在videopath的位置
		} else if (ImageTypeEnum.IMG.value().equals(attachmentDefinition.getType())) {
			attachment.setFilePath(filePath);
		}
		// 是否读取图片的高宽
		try {
			BufferedImage image = ImageIO.read(is);
			if (image != null) {
				attachment.setWidth(Long.valueOf(image.getWidth()));
				attachment.setHeight(Long.valueOf(image.getHeight()));
			}
		} catch (IOException e) {
			log.error("get image width and height error {}", e.toString());
		}
		return attachmentService.saveAttachment(attachment);// 保存到附件表
	}


	public AttachmentService getAttachmentService() {
		return attachmentService;
	}

	public void setAttachmentService(AttachmentService attachmentService) {
		this.attachmentService = attachmentService;
	}

	public void setScaleList(Map<String, List<Integer>> scaleList) {
		this.scaleList = scaleList;
	}

}
